<style>
.find-app {
  overflow-y: hidden;
  overflow-x: hidden;
}
</style>
  <div class="find-app" id="app">
    <!-- public-head -->
    <div class="header-mobile">
      <a class="nav-back" href="javascript:history.go(-1)">
        <img class="icon" src="__CDN__/assets/img/return@2x.png" alt="">
      </a>
      <h1 class="nav-title">{$name}</h1>
    </div>
    <!-- main-wrapepr -->
    <div class="main-wrapper">
      <div class="message-room-wrapper">
        <div class="create-time">温馨提示：请勿在平台外私下交易，如造成收益损失，平台概不负责</div>
        <div class="session-list" ref="scroller">
          <mt-loadmore :top-method="loadTop" @top-status-change="handleTopChange">
            <div class="inner" v-for="(item,index) in messageList" :key="index">
              <div class="post-time">{{item.time}}</div>
              <div :class="item.type === 'you'?'left':'right'" class="session-item">
                <img class="avatar" :src="item.avatar" alt="">
                <div class="txt">{{item.content}}</div>
              </div>
            </div>
            <div slot="top" class="mint-loadmore-top">
              <span v-show="topStatus !== 'loading'" :class="{ 'rotate': topStatus === 'drop' }">↓</span>
              <span v-show="topStatus === 'loading'">Loading...</span>
            </div>
          </mt-loadmore>
        </div>
      </div>
    </div>
    <!-- message-footer -->
    <div class="message-footer">
      <input class="input" @fou v-model='socketContent' placeholder="请输入发送内容..." type="text">
      <div class="btn" class="发送" @click="websocketsend">发送</div>
    </div>

  </div>
  </body>

  </html>
  <script src='https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js'></script>
  <script>
    $(function(){
      $('.input').on('blur',function(){
        window.scroll(0,0);
      });
      $('.input').on('change',function(){
        window.scroll(0,0);
      });
    })
    let room = new Vue({
      el: '#app',
      data: {
        page: 1,
        id: '{$user_id}',
        user_id: '{$chat_user_id}',
        chat_id: '{$chat_id}',
        reply_user_id: '{$reply_user_id}',
        something_id: '{$something_id}',
        messageList: [],
        topStatus: '',
        socketContent: ''
      },
      mounted() {
        // 获取原始聊天记录
        this.ajax()
        // 建立长链接
        this.initWebSocket()
      },
      methods: {
        initSocketUid() {
          let self = this;
          let uid_factory = {
            id: self.id,
            user_id: self.user_id,
            reply_user_id: self.reply_user_id,
            something_id: self.something_id
          }
          console.log('before:' + JSON.stringify(uid_factory))
          // 重构
          if (uid_factory.id === uid_factory.user_id) {
            uid_factory.id = uid_factory.reply_user_id
          } else {
            uid_factory.id = uid_factory.user_id
          }
          console.log('after:' + JSON.stringify(uid_factory))
          return JSON.stringify(uid_factory)
        },
        loadTop() {
          this.ajax()
        },
        handleTopChange(status) {
          this.topStatus = status;
        },
        initWebSocket() {
          let self = this
          var socket = io('http://47.112.115.217:2120');
          let init_uid = JSON.stringify({
            id: self.id,
            user_id: self.user_id,
            reply_user_id: self.reply_user_id,
            something_id: self.something_id
          })
          console.log('socket初始化:' + init_uid)
          // 前端链接服务
          socket.on('connect', function () {
            socket.emit('login', init_uid);
          });
          // login连接成功的回调
          socket.on('new_msg_ok', function (msg) {
            self.$toast({
              message: '连接聊天室成功!'
            })
          });
          // 接收别人发来的消息
          socket.on('new_msg', function (msg) {
            console.log('来自对方发送的消息！' + msg)
            self.messageList.push(JSON.parse(msg))
            console.log(self.messageList)
            self.scrollToBottom()
          });
        },
        websocketsend() { //数据发送
          let self = this;
          let after_uid = this.initSocketUid()
          if(self.socketContent.length<=0){
              self.$messagebox('发送的消息不能为空')
              return false;
          }
          console.log('发送数据执行id切换:' + after_uid)
          $.ajax({
            url: `http://47.112.115.217:2121?type=publish&content=${self.socketContent}&to=${after_uid}`,
            type: "GET",
            dataType: "jsonp", //指定服务器返回的数据类型
            jsonp: 'callback',
            jsonpCallback: 'flightHandler',
            success: function (data) {
              console.log('提交我的消息成功！' + data)
              self.messageList.push(JSON.parse(data))
              console.log(self.messageList)
              self.socketContent = ''
              self.scrollToBottom()
            },
            error: function (e) {
              console.log(e)
            }
          });
        },
        scrollToBottom() {
          let self = this
          this.$nextTick(() => {
            var container = self.$refs.scroller;
            console.log(container.scrollHeight)
            container.scrollTop = container.scrollHeight-100
          })
        },
        ajax() {
          let self = this;
          axios({
            method: "post",
            url: "{:url('index/messageroom')}",
            data: {
              page: self.page,
              chat_id: self.chat_id
            },
            headers: {
              'X-Requested-With': 'XMLHttpRequest'
            }
          }).then(res => {
            if (res.data.code == 1) {
              let data = res.data.data
              self.page++;
              for (let i in data) {
                self.messageList.unshift(data[i])
              }
              console.log(self.messageList)
            }
          })
        }
      }
    })
  </script>